﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using RN.ERP.Web.Utilities;

namespace RN.ERP.Web.Person
{
    public partial class PersonEmpCertInfo14 : BasePage
    {
        ////当前市场
        protected string CurrentArea
        {
            get
            {
                return UserInfo.CurrentArea;
            }
        }

        ////当前登录用户Guid
        private string CorpUserGuid
        {
            get
            {
                return UserInfo.CorpUserGuid;
            }
        }

        /// <summary>
        /// 用户类型
        /// </summary>
        protected string UserRole
        {
            get
            {
                return UserInfo.RoleType;
            }
        }

        /// <summary>
        /// 页面编辑状态
        /// </summary>
        protected int EditStatus
        {
            get;
            set;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetParams();
            }
        }
        public override bool IsCheckPermission
        {
            get { return false; }
        }
        /// <summary>
        /// 获取传递参数
        /// </summary>
        private void GetParams()
        {
            Guid empGuid = Guid.Empty;
            Guid certGuid = Guid.NewGuid();
            int opt = 0;
            if (!string.IsNullOrEmpty(Request.QueryString["empGuid"]))
            {
                if (Guid.TryParse(Request.QueryString["empGuid"], out empGuid))
                {
                    hdEmpGuid.Value = empGuid.ToString();
                }
            }
            if (!string.IsNullOrEmpty(Request.QueryString["certGuid"]))
            {
                if (Guid.TryParse(Request.QueryString["certGuid"], out certGuid))
                {
                    hdStatus.Value = "1";
                }
            }
            hdEducationGUID.Value = certGuid.ToString();
            ////人员类型分组
            int groupId = 0;
            if (Request.QueryString["groupId"] != null)
            {
                int.TryParse(Request.QueryString["groupId"].Trim(), out groupId);
                hdGroupTreeId.Value = groupId.ToString();
            }
            ///证书类别标识
            if (!string.IsNullOrEmpty(Request.QueryString["manual"]))
            {
                hdManualID.Value = Request.QueryString["manual"];
                lblTitle.Text = "";
            }
            if (!string.IsNullOrEmpty(Request.QueryString["title"]))
            {
                lblTitleSub.Text = Request.QueryString["title"];
                lblTitle.Text = Request.QueryString["title"];
            }
            ////可编辑显示状态（1：内容不可编辑，2：所有不可用）
            if (!string.IsNullOrEmpty(Request.QueryString["opt"]))
            {
                int.TryParse(Request.QueryString["opt"], out opt);
            }
            EditStatus = opt;
            ////判断编辑权限
            string classid = "2611";
            if (hdStatus.Value == "1")
            {
                string flowCode=CheckCertFlowCode(out classid);
                ucShenHeState.ClassId = classid;
                ucShenHeState.FlowCode = flowCode;
                ucShenHeState.AreaCode = CurrentArea;
            }
            else
            {
                string flowCode = CheckCertFlowCode(out classid);
                ucShenHeState.ClassId = classid;
                ucShenHeState.FlowCode = flowCode;
                ucShenHeState.AreaCode = CurrentArea;
                ucShenHeState.Visible = false;
            }
            SetBtnShowStatus();
            ////异步调用方法
            if (Request.Params["action"] != null)
            {
                string action = Request.Params["action"];
                switch (action)
                {
                    case "QualitieAdd":
                        QualitieSave(true, empGuid);
                        break;
                    case "QualitieEdit":
                        QualitieSave(false, empGuid);
                        break;
                    case "GetQualities":
                        GetQualities(empGuid.ToString(), certGuid.ToString());
                        break;
                    case "GetQualitiesDic":
                        GetQualitiesDic();
                        break;
                    case "GetCodeValid":
                        GetQualityCodeValid();
                        break;
                    case "CheckCodeValid":
                        CheckQualityCodeValid();
                        break;
                }
            }
        }
        /// <summary>
        /// 设置按钮显示状态
        /// </summary>
        private void SetBtnShowStatus()
        {
            if (EditStatus == 2)
            {
                certImgDiv.Visible = false;//上传图片
                btnSaveDiv.Visible = false;//保存
            }
        }
        /// <summary>
        /// 取得证书下拉列表
        /// </summary>
        /// <param name="rootCode"></param>
        /// <param name="parentId"></param>
        private void GetQualitiesDic()
        {
            string rootCode = string.Empty;
            int parentId = 0;
            int itemFlag = 0;
            string itemType = string.Empty;
            if (Request.Params["rootCode"] == null)
            {
                var result1 = "{\"result\":1,\"message\":\"参数错误！\"}";
                OutputData(result1);
                return;
            }
            rootCode = Request.Params["rootCode"];
            if (Request.Params["parentId"] != null)
            {
                int.TryParse(Request.Params["parentId"].ToString(), out parentId);
            }
            if (Request.Params["itemFlag"] != null)
            {
                int.TryParse(Request.Params["itemFlag"].Trim(), out itemFlag);
            }
            if (Request.Params["itemType"] != null)
            {
                itemType = Request.Params["itemType"].ToString().Trim();
            }
            using (BasicService.BasicServiceClient client = new BasicService.BasicServiceClient())
            {
                //返回全部证书类型
                if (string.IsNullOrEmpty(itemType))
                {
                    var ret = JsonConvert.DeserializeObject<List<ModelService.DictQualityInfo>>(client.GetQualitiesDic(rootCode, parentId.ToString()));
                    if (rootCode == "specialty" && ret != null)
                    {
                        if (ret.Count == 0)
                        {
                            ret = JsonConvert.DeserializeObject<List<ModelService.DictQualityInfo>>(client.GetQualitiesDic(rootCode, "0"));
                        }
                    }
                    OutputData(JsonConvert.SerializeObject(ret));
                    return;
                }
                //过滤参数传递的证书类型
                string[] itemAttr = itemType.Split(',');
                var list = JsonConvert.DeserializeObject<List<ModelService.DictQualityInfo>>(client.GetQualitiesDic(rootCode, parentId.ToString()));
                if (itemFlag == 0)
                {
                    //只返回参数中的证书类型
                    list = list.Where(l => itemAttr.Contains(l.Code)).ToList();
                }
                else
                {
                    //返回不包含在参数中的证书类型
                    list = list.Where(l => !itemAttr.Contains(l.Code)).ToList();
                }
                OutputData(JsonConvert.SerializeObject(list));
            }
        }
        /// <summary>
        /// 取得证书编号验证信息
        /// </summary>
        /// <param name="rootCode"></param>
        /// <param name="parentId"></param>
        private void GetQualityCodeValid()
        {
            string code = string.Empty;
            int itemFlags = 0;
            int certLevel = 0;
            string areaCode = UserInfo.CurrentArea;
            if (Request.Params["code"] != null)
            {
                code = Request.Params["code"].ToString().Trim();
            }
            if (Request.Params["typeFlags"] != null)
            {
                int.TryParse(Request.Params["typeFlags"].Trim(), out itemFlags);
            }
            if (Request.Params["certLevel"] != null)
            {
                int.TryParse(Request.Params["certLevel"].Trim(), out certLevel);
            }
            using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
            {
                OutputData(client.GetQualityCodeValid(code, itemFlags.ToString(), certLevel.ToString(), areaCode));
                return;

            }
        }
        /// <summary>
        /// 验证证书编号格式
        /// </summary>
        private void CheckQualityCodeValid()
        {
            string code = string.Empty;
            int itemFlags = 0;
            int certLevel = 0;
            string certCode = string.Empty;
            string areaCode = UserInfo.CurrentArea;
            if (Request.Params["code"] != null)
            {
                code = Request.Params["code"].ToString().Trim();
            }
            if (Request.Params["certCode"] != null)
            {
                code = Request.Params["certCode"].ToString().Trim();
            }
            if (Request.Params["typeFlags"] != null)
            {
                int.TryParse(Request.Params["typeFlags"].Trim(), out itemFlags);
            }
            if (Request.Params["certLevel"] != null)
            {
                int.TryParse(Request.Params["certLevel"].Trim(), out certLevel);
            }
            using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
            {
                OutputData(client.CheckQualityCodeValid(code, itemFlags.ToString(), certLevel.ToString(), certCode, areaCode));
                return;

            }
        }
        /// <summary>
        ///查询证书信息
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="AreaCode"></param>
        private void GetQualities(string empGuid, string certGuid)
        {
            Guid certGuid1 = Guid.Empty;
            Guid.TryParse(certGuid, out certGuid1);
            Guid empGuid1 = Guid.Empty;
            Guid.TryParse(empGuid, out empGuid1);
            if (empGuid1 == Guid.Empty || certGuid1 == Guid.Empty)
            {
                var result1 = "{\"result\":1,\"message\":\"参数错误！\"}";
                OutputData(result1);
                return;
            }
            using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
            {
                var qualities = JsonConvert.DeserializeObject<List<ModelService.Tb_Emp_TitleDetails>>(client.GetEmpQualities(empGuid, UserInfo.CurrentArea));
                if (qualities != null)
                {
                    var query = JsonConvert.SerializeObject(qualities.Where(q => q.EducationGUID == certGuid1).FirstOrDefault());
                    var result = "{\"result\":0,\"data\":" + query + "}";
                    OutputData(result);
                }

            }
        }

        /// <summary>
        /// 添加修改信息
        /// </summary>
        private void QualitieSave(bool flag, Guid empGuid)
        {
            if (empGuid == Guid.Empty)
            {
                OutputData("{\"Result\":false,\"Message\":\"请先添加人员！\"}");
                return;
            }
            if (Request.Params["data"] == null)
            {
                OutputData("{\"Result\":false,\"Message\":\"数据错误！\"}");
                return;
            }
            string data = Request.Params["data"];//取得客户端提交的数据

            //转化数据对象
            var managers = JsonConvert.DeserializeObject<List<JsonEntity>>(Request.Params["data"]);
            List<ModelService.Tb_Emp_TitleDetails> empTD = null;
            foreach (var manager in managers)
            {
                var valStr = manager.value.Trim('\"');//对象值为json格式的Tb_Emp_TitleDetails对象
                empTD = JsonConvert.DeserializeObject<List<ModelService.Tb_Emp_TitleDetails>>(valStr);
            }
            if (empTD != null && empTD.Count > 0)
            {
                //验证资格证书扫描件
                string result1 = CheckPersonZGFile(empTD);
                if (result1 != null)
                {
                    OutputData(result1);
                }
                using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
                {
                    string result = "";
                    string corpGuid = UserInfo.CorpUserGuid;
                    //执行添加或修改操作
                    if (flag)
                    {

                        ModelService.tb_Emp_Manager person = JsonConvert.DeserializeObject<ModelService.tb_Emp_Manager>
                        (client.GetEmpManager(empGuid.ToString(), string.Empty));
                        if (person != null && person.ClassId != null)
                        {
                            int certClassId = 2511;
                            int.TryParse(person.ClassId.ToString(), out certClassId);
                            certClassId = certClassId + 100;
                            empTD.ForEach(o => o.ClassID = certClassId);
                        }
                        result = client.EmpQualityAdd(corpGuid, empGuid.ToString(), JsonConvert.SerializeObject(empTD), true, UserInfo.CurrentArea);

                    }
                    else
                    {
                        result = client.EmpQualityEdit(corpGuid, empGuid.ToString(), JsonConvert.SerializeObject(empTD), UserInfo.CurrentArea);
                    }
                    if (SystemID == "95")
                    {
                        ZhuanjiaLihaiDwCheck(result, empTD.FirstOrDefault(), flag);
                    }
                    OutputData(result);
                }
            }

        }

        /// <summary>
        /// 添加修改专家厉害单位
        /// </summary>
        /// <param name="empWork"></param>
        private void ZhuanjiaLihaiDwCheck(string result, ModelService.Tb_Emp_TitleDetails details, bool flag)
        {
            var result0 = JsonConvert.DeserializeObject<ModelService.OperationResult>(result);
            if (!result0.Result)
            {
                return;
            }
            if (details == null)
            {
                return;
            }
            if (details.RegisterCorpName == null || details.RegisterCorpName == "")
            {
                return;
            }
            if (flag)
            {
                ZhuanjiaLihaiDwAdd(details, UserInfo.CurrentArea);
            }
            else
            {
                ZhuanjiaLihaiDwEdit(details.EmpGuid.ToString(), details.RegisterCorpName.Trim(), UserInfo.CurrentArea);
            }
        }

        #region 专家利害关系操作
        /// <summary>
        /// 添加专家利害单位
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="entityName"></param>
        /// <param name="areaCode"></param>
        private void ZhuanjiaLihaiDwAdd(ModelService.Tb_Emp_TitleDetails details, string areaCode)
        {
            try
            {
                using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
                {
                    ModelService.tb_User_Relation model = new ModelService.tb_User_Relation();
                    model.Gid = Guid.NewGuid();
                    model.ID = 0;
                    model.UserGuid = details.EmpGuid ?? Guid.Empty;////empguid
                    model.CreateTime = DateTime.Now;
                    model.EntityFlag = 1;
                    model.EntityGuid = Guid.NewGuid();
                    model.EntityName = details.RegisterCorpName;////企业名称
                    model.AreaCode = areaCode;
                    model.AppId = 95;
                    model.Reason = "注册单位";
                    model.ClassId = 1002;
                    client.SaveUserRelationInfo(JsonConvert.SerializeObject(model), areaCode);
                }
            }
            catch { }
        }

        /// <summary>
        /// 修改专家利害单位
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="entityName"></param>
        /// <param name="areaCode"></param>
        private void ZhuanjiaLihaiDwEdit(string empGuid, string entityName, string areaCode)
        {
            try
            {
                string corpName = string.Empty;
                if (Request.Params["entityName"] != null)
                {
                    corpName = Request.Params["entityName"].Trim();
                }
                if (corpName != entityName.Trim())
                {
                    using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
                    {
                        var result = client.UpdateUserRelationCorp(empGuid, 1002, corpName, entityName.Trim(), areaCode);
                    }
                }
            }
            catch { }
        }

        #endregion

        /// <summary>
        /// 验证资格证书图片
        /// </summary>
        /// <param name="empTD"></param>
        /// <returns></returns>
        private string CheckPersonZGFile(List<ModelService.Tb_Emp_TitleDetails> empTD)
        {
            var titledtl = empTD.FirstOrDefault();
            if (titledtl == null)
            {
                return null;
            }
            if (titledtl.StampCode == "ZGZSLC" || titledtl.StampCode == "ZGZS-Expert")
            {
                string funcCodes = "PersonZG";
                string filenames = titledtl.EducationGUID.ToString();
                string result1 = UtilitiesTool.IsFileExists(filenames, "EF", funcCodes);
                if (!string.IsNullOrEmpty(result1))
                {
                    return "{\"Result\":false,\"Message\":\"img\",\"ReturnValue\":\"必须上传资格证书扫描件！\"}";
                }
            }
            return null;
        }

        /// <summary>
        /// 用户按钮显示及可编辑状态 获得flowcode和classid
        /// </summary>
        private string CheckCertFlowCode(out string classid)
        {
            string flowcode = string.Empty;
            classid = string.Empty;
            Dictionary<string, string> dic = GetCurrentFLowCode();
            if (dic != null)
            {
                flowcode = dic["flowcode"] == null ? "" : dic["flowcode"];
                classid = dic["classid"] == null ? "" : dic["classid"];
            }
            
            List<ModelService.OperationResult> resultList = GetFlowCodes();
            if (resultList == null)
            {
                return flowcode;
            }
            ////可以编辑
            if (!resultList[1].Result)
            {
                EditStatus=2;
            }
            return flowcode;
        }

        /// <summary>
        /// 取得人员证书审核状态组
        /// </summary>
        /// <returns>返回从添加到审核的所有操作状态集</returns>
        private List<ModelService.OperationResult> GetFlowCodes()
        {
            using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
            {
                var result = JsonConvert.DeserializeObject<ModelService.OperationResult>(client.GetCertFlowCode(CorpUserGuid, hdEducationGUID.Value.Trim(), 7, CurrentArea));
                if (!result.Result)
                {
                    //RadWindowManager1.RadAlert("人员信息异常，无法完成操作！", 300, 150, "提示", "");
                    return null;
                }
                //状态结果集
                return JsonConvert.DeserializeObject<List<ModelService.OperationResult>>(result.ReturnValue.ToString());
            }
        }

        /// <summary>
        /// 按Guid获取证书表审核状态和classid
        /// </summary>
        /// <returns></returns>
        private Dictionary<string, string> GetCurrentFLowCode()
        {
            using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
            {
                var result = JsonConvert.DeserializeObject<ModelService.OperationResult>(client.GetCertFlowByGuid(hdEducationGUID.Value.Trim(),CurrentArea));
                if (!result.Result)
                {
                    return null;
                }
                Dictionary<string, string> dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(result.ReturnValue.ToString());
                return dict;
            }
        }

        /// <summary>
        /// 输出JSON格式数据到页面
        /// </summary>
        /// <param name="dataStr"></param>
        private void OutputData(string dataStr)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Write(dataStr);
            HttpContext.Current.Response.End();
        }
    }
}
